package wili.exp.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import wili.c.Ca;
import wili.c.Math9a;
import wili.c.Misc9a;

/**
 * 
 * @author weilai
 *
 */
public class Sop extends Sexp {
	public String toString() {
		return this.toNumString(null);
	}

	@Override
	public String toNumString(Map cont) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sons.size(); i++) {
			if (i > 0)
				sb.append(op);
			Sexp son = sons.get(i);
			sb.append(son.toNumString(cont));
		}
		return sb.toString();
	}

	@Override
	public Boolean isTrue(Map cont) {
		Ca.asert(sons.size() == 2, "");
		if (op.equals("%"))
			Ca.pause();
		Sexp ll = sons.get(0), rr = sons.get(1);
		Object is1 = ll.value(cont);
		Object is2 = rr.value(cont);
		return Math9a.compare(is1, op, is2);
	}

	@SuppressWarnings("all")
	@Override
	public <T> T value(Map map) {
		int ind = Misc9a.indexOf(op, "=", "+=", "-=", "*=", "/=");
		if (ind != -1) {
			Ca.asert(sons.size() == 2, sons);
			Sexp va = sons.get(0);
			Ca.asert(va instanceof Svar, va);
			Object rr = sons.get(1).value(map);
			rr = Math9a.count(map.get(va.name), op, rr);
			map.put(va.name, rr);
			return (T) rr;
		}
		List<Number> nn = new ArrayList<>(sons.size());
		for (int i = 0; i < this.sons.size(); i++) {
			Sexp son = sons.get(i);
			nn.add(son.value(map));
		}
		T ret = Math9a.countList(op, nn);
		return ret;
	}

	public Sop(Node node) {
		super(node);
		this.op = node.text;
		List<Node> nodSons = node.sons;
		sons = new ArrayList<>(nodSons.size());
		for (int i = 0; i < nodSons.size(); i++) {
			Node nodSon = nodSons.get(i);
			if (nodSon.isOp) {
				sons.add(new Sop(nodSon));
				continue;
			}
			sons.add(Sexp.newInst(nodSon));
		}
	}
}
